package org.realogic.cfm.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public final class UtilProperty {

	private ResourceBundle bundle;

	public static UtilProperty get(String baseName) {
		ResourceBundle bundle = ResourceBundle.getBundle(baseName);
		return new UtilProperty(bundle);
	}

	private UtilProperty(ResourceBundle bundle) {
		this.bundle = bundle;
	}

	public Map<String, String> getProtertyMap() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> e = bundle.getKeys();
		while (e != null && e.hasMoreElements()) {
			String key = e.nextElement();
			map.put(key, bundle.getString(key));
		}
		return map;
	}

	public String getAsString(String key) {
		try {
			String s = bundle.getString(key);
			return s == null ? null : s.trim();
		} catch (MissingResourceException e) {
			return null;
		}
	}

	public int getAsInt(String key) {
		try {
			String propertyValue = getAsString(key);
			return Integer.parseInt(propertyValue);
		} catch (Exception e) {
			return 0;
		}
	}

	public long getAsLong(String key) {
		try {
			String propertyValue = getAsString(key);
			return Long.parseLong(propertyValue);
		} catch (Exception e) {
			return 0;
		}
	}

	public boolean getAsBoolean(String key) {
		String propertyValue = getAsString(key);
		if (propertyValue == null) {
			return false;
		}
		if (propertyValue.length() == 0) {
			return false;
		}
		if (propertyValue.equalsIgnoreCase("1")) {
			return true;
		}
		if (propertyValue.equalsIgnoreCase("0")) {
			return false;
		}
		if (propertyValue.equalsIgnoreCase("y")) {
			return true;
		}
		if (propertyValue.equalsIgnoreCase("n")) {
			return false;
		}
		if (propertyValue.equalsIgnoreCase("on")) {
			return true;
		}
		if (propertyValue.equalsIgnoreCase("off")) {
			return false;
		}

		return Boolean.getBoolean(propertyValue);
	}
}
